﻿using System;
using System.Net;
using System.Net.Mail;
using ABC.Core.Configuration;
using ABC.Core.Providers;
using Castle.Core.Logging;

namespace ABC.Business.Models
{
    public class SmtpClientModel
    {
        private readonly SmtpClient smtpClient; 
        private readonly IApplicationSettingsProvider applicationSettingsProvider; 
        private readonly string from;

        public SmtpClientModel(IApplicationSettingsProvider applicationSettingsProvider)
        {
            this.applicationSettingsProvider = applicationSettingsProvider; 
            var settings = this.applicationSettingsProvider.SmtpMailSettings;
            smtpClient = new SmtpClient(); 
            smtpClient.DeliveryMethod = settings.DeliveryMethod;
            smtpClient.Host = settings.Network.Host;
            smtpClient.Port = settings.Network.Port;
            smtpClient.EnableSsl = settings.Network.EnableSsl;
            smtpClient.Credentials = new NetworkCredential(settings.Network.UserName, settings.Network.Password);
            from = settings.From;
        }

        public bool Send(string to, string subject, string body)
        {
            return Send(to, subject, body, false);
        }

        public bool Send(string to, string subject, string body, bool isHtml)
        {
            try
			{
                var message = new MailMessage();

                message.From = new MailAddress(from);
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = isHtml;

                smtpClient.Send(message);
            }
            catch (Exception e)
            {
                IoC.Resolve<ILogger>().Error(e.Message); 
                return false;
            }

            return true;
        }
    }
}